package com.lemon.smartsafetynew.ui.activity.me;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.net.services.AccountServices;
import com.lemon.smartsafetynew.util.common.AppSharePreferenceUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * Created by Andrew on 2017/7/12.
 */

public class MeModifiedUserNameActivity extends SwipeBackActivity {

    @Bind(R.id.user_name_edit)
    EditText userNameEdit;
    @Bind(R.id.sure_btn)
    Button sureBtn;
    @Bind(R.id.user_name_error_info_tv)
    TextView userNameErrorInfoTv;

    private MaterialDialog materialDialog;

    @Override
    protected void initTitle() {

        this.setBarTitle(getString(R.string.me_options_group_1_2));
        mToolBar.setContentInsetsAbsolute(0, 0);

    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(MeModifiedUserNameActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_modified_user_name;
    }

    @Override
    protected void initViews() {
        super.initViews();

        userNameEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                userNameErrorInfoTv.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick(R.id.sure_btn)
    public void onViewClicked() {

        String userName = userNameEdit.getText().toString().trim();

        if (checkUserName(userName) && matcherUserName(userName)) {

            LemonRequestParams params = new LemonRequestParams("");
            params.put("user_name", userName);
            AccountServices
                    .init()
                    .changeUserName(params);

        } else {
            userNameErrorInfoTv.setText(getString(R.string.user_name_format_error));
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent<String> event) {
        if (KeyConstants.URL_CHANGE_USER_NAME.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                showDialog();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                cancelDialog();
                if (event.getEventResult() == Constants.Result.SUCCESS) {

                    Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                    User user = AccountUtil.getUser();
                    if(user != null) {
                        user.setUserName(event.getObj());
                    }
                    AppSharePreferenceUtil.getInstance().putString(SafeCloudConstants.CURRENT_USER, new Gson().toJson(user));

                    callFinish();

                } else {
                    Toast.makeText(this, event.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private boolean checkUserName(String userName) {
        return !(null == userName || "".equals(userName));
    }

    private boolean matcherUserName(String userName) {

        String pattern = "^[\\u4e00-\\u9fa5A-Za-z0-9]{2,12}$";
        Pattern mPattern = Pattern.compile(pattern);
        Matcher mMatcher = mPattern.matcher(userName);

        return mMatcher.matches();
    }

    private void showDialog() {
        materialDialog = new MaterialDialog.Builder(MeModifiedUserNameActivity.this)
                .content(R.string.please_wait)
                .progress(true, 0)
                .cancelable(false)
                .show();
    }

    private void cancelDialog() {
        if (materialDialog != null && materialDialog.isShowing()) {
            materialDialog.dismiss();
            materialDialog = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelDialog();
    }

}
